package org.handover.Tools;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class Tools {
    public static String getMessages(HttpServletRequest httpServletRequest, String code, String defaultMessage){
        RequestContext requestContext = new RequestContext(httpServletRequest);
        return requestContext.getMessage(code, defaultMessage);
    }

    public static Boolean hasRole(String role){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetails) {
            for (GrantedAuthority grantedAuthority:((UserDetails)principal).getAuthorities()){
                if (grantedAuthority.getAuthority().equals("ROLE_"+role)) return true;
                System.out.println(grantedAuthority.getAuthority());
            }
            return false;
        } else {
            return false;
            //String username = ((UserDetails)principal).getUsername();
            //String username = principal.toString();
            //System.out.println(username);
        }
/*
        SecurityContextImpl securityContextImpl = (SecurityContextImpl) request
                .getSession().getAttribute("SPRING_SECURITY_CONTEXT");
// 登录名
        System.out.println("Username:"
                + securityContextImpl.getAuthentication().getName());
// 登录密码，未加密的
        System.out.println("Credentials:"
                + securityContextImpl.getAuthentication().getCredentials());
        WebAuthenticationDetails details = (WebAuthenticationDetails) securityContextImpl
                .getAuthentication().getDetails();
// 获得访问地址
        System.out.println("RemoteAddress" + details.getRemoteAddress());
// 获得sessionid
        System.out.println("SessionId" + details.getSessionId());
// 获得当前用户所拥有的权限
        List<GrantedAuthority> authorities = (List<GrantedAuthority>) securityContextImpl
                .getAuthentication().getAuthorities();
        for (GrantedAuthority grantedAuthority : authorities) {
            System.out.println("Authority" + grantedAuthority.getAuthority());
        }
*/
    }
}
